#!/bin/sh

#
# This script copies the id.txt and/or config.xml
# created by the web installer to the application bundle folder
# OR
# gets the back up copy of a previously existing id.txt and/or
# config.xml
#
# The temporary app bundle is also renamed if needed
#
# Note that this script currently executes before the installer
# plug-in, based on the order currently specified in
# InstallerSections.plist
#

echo "Postflight" >> /tmp/script.log
date >> /tmp/script.log

APPBUNDLENAME="LockDown Browser.app"
TMPBUNDLENAME="LockDown Browser (unconfigured).app"
IDFILE="id.txt"
CFGFILE="config.xml"

echo "Arg1 = $1" >> /tmp/script.log
echo "Arg2 = $2" >> /tmp/script.log
echo "Arg3 = $3" >> /tmp/script.log
echo "Arg4 = $4" >> /tmp/script.log

echo "Working Directory is : " `pwd` >> /tmp/script.log

# if necessary, rename temp bundle to final app name;
# note that here we are overwriting any existing install
#   with the same app name brand (or some other app with
#   the same name) in the same folder
if [ -e "$2/$TMPBUNDLENAME" ]
then
	if [ -e "$2/$APPBUNDLENAME" ]
	then
		rm -r "$2/$APPBUNDLENAME"
	fi
	mv "$2/$TMPBUNDLENAME" "$2/$APPBUNDLENAME" >> /tmp/script.log
fi

# give priority to any id.txt provided with the installer package
# over any previous id.txt
if [ -e "$1/Contents/Resources/$IDFILE" ]
then
	if [ -e "$2/$APPBUNDLENAME/$IDFILE" ]
	then
		rm "$2/$APPBUNDLENAME/$IDFILE"
	fi
	echo "Copying $1/Contents/Resources/$IDFILE to $2/$APPBUNDLENAME/$IDFILE" >> /tmp/script.log
	cp "$1/Contents/Resources/$IDFILE" "$2/$APPBUNDLENAME/$IDFILE" >> /tmp/script.log
elif [ ! -e "$2/$APPBUNDLENAME/$IDFILE" ]
then
	if [ -e "/tmp/LDBPreviousId.txt" ]
	then
		echo "Copying /tmp/LDBPreviousId.txt to $2/$APPBUNDLENAME/$IDFILE" >> /tmp/script.log
		cp "/tmp/LDBPreviousId.txt" "$2/$APPBUNDLENAME/$IDFILE" >> /tmp/script.log
		rm "/tmp/LDBPreviousId.txt"
	else
		echo "/tmp/LDBPreviousId.txt does not exist. Copy cancelled." >> /tmp/script.log
	fi
fi

# give priority to any config.xml provided with the installer package
#   over any previous config.xml
# probably don't need this, since updates will need to have a config.xml
#   for branding anyway, but here it is just in case
if [ -e "$1/Contents/Resources/$CFGFILE" ]
then
	if [ -e "$2/$APPBUNDLENAME/$CFGFILE" ]
	then
		rm "$2/$APPBUNDLENAME/$CFGFILE"
	fi
	echo "Copying $1/Contents/Resources/$CFGFILE to $2/$APPBUNDLENAME/$CFGFILE" >> /tmp/script.log
	cp "$1/Contents/Resources/$CFGFILE" "$2/$APPBUNDLENAME/$CFGFILE" >> /tmp/script.log
elif [ ! -e "$2/$APPBUNDLENAME/$CFGFILE" ]
then
	if [ -e "/tmp/LDBPreviousConfig.xml" ]
	then
		echo "Copying /tmp/LDBPreviousConfig.xml to $2/$APPBUNDLENAME/$CFGFILE" >> /tmp/script.log
		cp "/tmp/LDBPreviousConfig.xml" "$2/$APPBUNDLENAME/$CFGFILE" >> /tmp/script.log
		rm "/tmp/LDBPreviousConfig.xml"
	else
		echo "/tmp/LDBPreviousConfig.xml does not exist. Copy cancelled." >> /tmp/script.log
	fi
fi
